<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表的搜索和排序</title>
</head>
<body>

<div id="test">
    <input type="text" v-model="searchName">
    <ul>
        <li v-for="(p,index) in filterPersons" :key="index">
            {{index}} ---- {{p.name}} ---- {{p.age}}
        </li>
    </ul>
    <button @click="setOrderType(1)">按年龄升序</button>
    <button @click="setOrderType(2)">按年龄降序</button>
    <button @click="setOrderType(0)">原来的顺序</button>
</div>
<script type=" text/javascript" src="../js/vue.js"></script>
<script>
    new Vue({
        el: '#test',
        data: {
            searchName: '',
            orderType: 0,// 0 表示原有的顺序 1：升序 2：降序
            persons: [
                {name: 'Tom', age: 18},
                {name: 'Jack', age: 16},
                {name: 'Bob', age: 19},
                {name: 'Rose', age: 17},
            ]
        },
        computed: {
            filterPersons() {
                // 取出相关的数据
                const {searchName, persons, orderType} = this
                // 对persons进行过滤
                let result;
                result = persons.filter(p => {
                    return p.name.indexOf(searchName) !== -1
                })
                if (orderType !== 0) {
                    result.sort(function (p1, p2) {
                        // 1：升序 2：降序
                        if (orderType === 2) {
                            return p2.age - p1.age
                        } else {
                            return p1.age - p2.age
                        }
                    })

                }
                return result;
            }
        },
        methods: {
            setOrderType(orderType) {
                this.orderType = orderType
            }
        }
    })

</script>
</body>
</html>